package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.storage.StorageService;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.ILiquormallLiquor;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.domain.UserVo;
import org.linlinjava.litemall.db.service.ILiquormallLiquorService;
import org.linlinjava.litemall.db.service.LitemallCollectService;
import org.linlinjava.litemall.db.service.LitemallStorageService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.GetRegionService;
import org.linlinjava.litemall.wx.service.WxLiquorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx/liquor")
@Api(tags = "酒友圈类")
@Validated
public class WxIliquormallLiquorController {
    private final Log logger = LogFactory.getLog(WxIliquormallLiquorController.class);


    @Autowired
    private ILiquormallLiquorService iLiquormallLiquorService;

    @Autowired
    private WxLiquorService wxLiquorService;

    @Autowired
    private LitemallStorageService litemallStorageService;

    @Autowired
    private StorageService storageService;

    @Autowired
    private GetRegionService getRegionService;

    @Autowired
    private LitemallCollectService litemallCollectService;

    @Autowired
    private ILiquormallLiquorService liquorService;

    @Autowired
    private LitemallUserService userService;

    /**
     * 小程序端新增商品
     *
     * @param userId 用户ID
     * @param body
     */
    @ApiOperation("新增酒友圈")
    @PostMapping("/add")
    public Object add(@LoginUser Integer userId, @RequestBody String body) {
        return wxLiquorService.wxAdd(userId, body);
    }

    /**
     * 小程序端删除商品
     *
     * @param userId 用户ID
     * @param id
     */
    @PostMapping("/delete")
    public Object delete(@LoginUser Integer userId, @RequestParam Integer id) {
        int i = iLiquormallLiquorService.deleteById(userId, id);
        if (i == 0) {
            return ResponseUtil.ok();
        } else {
            return ResponseUtil.fail(1, "不是当前用户发布的酒源信息，不可删");
        }
    }

    /**
     * 上传照片回显功能
     */
    @ApiOperation("废弃，不用")
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        LitemallStorage litemallStorage = storageService.store(file.getInputStream(), file.getSize(), file.getContentType(), originalFilename);
        Map<String, Object> entity = new HashMap<>();
        entity.put("litemallStorage", litemallStorage);
        return ResponseUtil.ok(entity);
    }

    /**
     * 分页查询个人发布酒友圈
     */
    @ApiOperation("我的发布中展示的酒友圈")
    @GetMapping("/list/my")
    public Object listMy(@LoginUser Integer userId) {
        List<ILiquormallLiquor> iLiquormallLiquorList = iLiquormallLiquorService.queryListMy(userId);
        Map<String, Object> entity = new HashMap<>();
        entity.put("iLiquormallLiquorList", iLiquormallLiquorList);
        return ResponseUtil.ok(entity);
    }


    /**
     * 分页查询酒友圈
     */
    @ApiOperation("首页的酒友圈显示，这里只返回5个")
    @GetMapping("/list/new")
    public Object listLimitFive() {
        List<ILiquormallLiquor> iLiquormallLiquorList = iLiquormallLiquorService.queryListLimitFive();
        Map<String, Object> entity = new HashMap<>();
        entity.put("iLiquormallLiquorList", iLiquormallLiquorList);
        return ResponseUtil.ok(entity);
    }

    /**
     * 分页查询酒友圈
     */
    @ApiOperation("酒友圈列表展示，无条件")
    @GetMapping("/list")
    public Object list() {
        List<ILiquormallLiquor> iLiquormallLiquorList = iLiquormallLiquorService.queryList();
        Map<String, Object> entity = new HashMap<>();
        entity.put("iLiquormallLiquorList", iLiquormallLiquorList);
        return ResponseUtil.ok(entity);
    }

    /**
     * 查询酒友圈
     *
     * @param title
     * @param page
     * @param limit
     * @return
     */
    @ApiOperation("根据title分页查询酒友圈")
    @GetMapping("/list/title")
    public Object listTitle(@RequestParam String title,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "20") Integer limit) {
        return liquorService.queryListByTitle(title, page, limit);
    }

    /**
     * 根据条件分页查询酒友圈
     * 交易类型：求购/出售  userType
     * 类别：坤沙/碎沙/成品酒  liquorType
     * 酒龄  age
     * 价格 price
     */
    @ApiOperation("根据条件分页查询酒友圈")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = "limit", value = "每页显示记录数", paramType = "query",required = true, dataType="int"),
            @ApiImplicitParam(name = "body", value = "json格式的主体，根据其中的内容进行筛选；userType传的是汉字，买家/卖家；liquorType传的是汉字，坤沙/碎沙/成品酒；age和price都是asc/desc", paramType = "query", required = true, dataType="String")
    })
    @PostMapping("/listBySit")
    public Object listBySit(@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer limit,
                            @RequestBody String body) {
        ILiquormallLiquor query = new ILiquormallLiquor();
        if (!StringUtils.isEmpty(JacksonUtil.parseString(body, "userType"))) {
            query.setUserType(JacksonUtil.parseString(body, "userType"));
        }
        if (!StringUtils.isEmpty(JacksonUtil.parseString(body, "liquorType"))) {
            query.setLiquorType(JacksonUtil.parseString(body, "liquorType"));
        }
        if (!StringUtils.isEmpty(JacksonUtil.parseString(body, "age"))) {
            query.setAge(JacksonUtil.parseString(body, "age"));
        } else if (!StringUtils.isEmpty(JacksonUtil.parseString(body, "price"))) {
            query.setPrice(JacksonUtil.parseString(body, "price"));
        }


        List<ILiquormallLiquor> iLiquormallLiquorList = iLiquormallLiquorService.queryListBySit(page, limit, query);
        Map<String, Object> entity = new HashMap<>();
        entity.put("iLiquormallLiquorList", iLiquormallLiquorList);
        return ResponseUtil.ok(entity);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/queryone")
    public Object queryOne(@RequestParam Integer id) {
        ILiquormallLiquor iLiquormallLiquor = iLiquormallLiquorService.queryById(id);
        Map<String, Object> entity = new HashMap<>();
        entity.put("iLiquormallLiquor", iLiquormallLiquor);
        return ResponseUtil.ok(entity);
    }

    @GetMapping("/detail")
    public Object detail(@LoginUser Integer userId, @NotNull Integer id) {
        ILiquormallLiquor iLiquormallLiquor = iLiquormallLiquorService.queryById(id);
        // 用户收藏
        int userHasCollect = 0;
        if (userId != null) {
            userHasCollect = litemallCollectService.count(userId, (byte) 0, id);
        }

        UserVo user = null;
        if (iLiquormallLiquor != null){
            user = userService.findUserVoById(iLiquormallLiquor.getUserId());
        }

        Map<String, Object> entity = new HashMap<String, Object>();
        entity.put("iLiquormallLiquor", iLiquormallLiquor);
        entity.put("userHasCollect", userHasCollect);
        entity.put("user", user);
        return ResponseUtil.ok(entity);
    }

}
